package com.jingfang.cloud.widget.check;

import com.fazecast.jSerialComm.SerialPort;
import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Spacer;
import com.jingfang.cloud.MzContext;
import com.jingfang.cloud.MzPrefs;
import com.jingfang.cloud.core.SerialPortService;
import com.jingfang.cloud.widget.main.MainWidget;
import lombok.Getter;
import org.dromara.quickswing.ui.app.QSWidget;

import javax.swing.*;
import javax.swing.plaf.FontUIResource;
import javax.swing.text.StyleContext;
import java.awt.*;
import java.util.Arrays;
import java.util.Locale;

@Getter
public class CheckComponent {
    private final QSWidget<MzPrefs> owner;
    private final MzContext context;
    private final MzPrefs prefs;
    private JComboBox<String> serialPortComboBox;
    private JButton openSerialPortBtn;
    private JPanel contentPanel;
    private JLabel messageLabel;
    private JButton scanBtn;


    public CheckComponent(QSWidget<MzPrefs> owner) {
        this.owner = owner;
        this.context = (MzContext) owner.getContext();
        this.prefs = owner.getPrefs();
        this.findAvailableSerialPort();
        this.scanBtn.addActionListener(e -> this.findAvailableSerialPort());
        this.openSerialPortBtn.addActionListener(e -> {
            Object selectedItem = serialPortComboBox.getSelectedItem();
            if (selectedItem == null) {
                messageLabel.setText("<html><font color='GREEN'>没有发现可用的串口.</font></html>");
                return;
            }
            SerialPortService serialPortService = new SerialPortService(context, (String) selectedItem);
            if (serialPortService.openSerialPort()) {
                MainWidget mainWidget = new MainWidget(context, getOwner().getTitle(), prefs, serialPortService);
                mainWidget.setLocationRelativeTo(null);
                mainWidget.setVisible(true);
                this.owner.dispose();
            } else {
                messageLabel.setText("<html><font color='orange'>脉诊仪串口打开失败.</font></html>");
            }
        });
    }

    public void findAvailableSerialPort() {
        try {
            SerialPort[] availablePorts = SerialPort.getCommPorts();
            int selectedIndex = 0;
            for (int i = 0; i < availablePorts.length; i++) {
                SerialPort availablePort = availablePorts[i];
                if ("STM32 Virtual ComPort".equals(availablePort.getPortDescription())) {
                    selectedIndex = i;
                }
                Object[] selectedObjects = serialPortComboBox.getSelectedObjects();
                boolean noneMatch = Arrays.stream(selectedObjects).noneMatch(o -> o.equals(availablePort.getSystemPortName()));
                if (noneMatch) {
                    serialPortComboBox.addItem(availablePort.getSystemPortName());
                }
            }
            if (selectedIndex != 0) {
                serialPortComboBox.setSelectedIndex(selectedIndex);
                serialPortComboBox.setEnabled(false);
                openSerialPortBtn.setVisible(true);
                scanBtn.setVisible(false);
                messageLabel.setText("<html><font color='GREEN'>已成功检测到脉诊仪串口信息.</font></html>");
            } else {
                openSerialPortBtn.setVisible(false);
                messageLabel.setText("<html><font color='orange'>未检测到脉诊仪可用串口.</font></html>");
                messageLabel.setToolTipText("请检查驱动是否安装正确，脉诊仪USB接口是否有松动！");
            }
        } catch (Exception e) {
            openSerialPortBtn.setVisible(false);
            messageLabel.setText("<html><font color='RED'>未检测到可用串口异常.</font></html>");
        }


    }

    {
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
        $$$setupUI$$$();
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayoutManager(4, 6, new Insets(0, 0, 0, 0), -1, -1));
        serialPortComboBox = new JComboBox();
        Font serialPortComboBoxFont = this.$$$getFont$$$(null, -1, 16, serialPortComboBox.getFont());
        if (serialPortComboBoxFont != null) serialPortComboBox.setFont(serialPortComboBoxFont);
        contentPanel.add(serialPortComboBox, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, new Dimension(150, -1), new Dimension(100, -1), null, 0, false));
        final Spacer spacer1 = new Spacer();
        contentPanel.add(spacer1, new GridConstraints(3, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        final JLabel label1 = new JLabel();
        Font label1Font = this.$$$getFont$$$(null, -1, 16, label1.getFont());
        if (label1Font != null) label1.setFont(label1Font);
        label1.setText("串口信息");
        contentPanel.add(label1, new GridConstraints(1, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        openSerialPortBtn = new JButton();
        Font openSerialPortBtnFont = this.$$$getFont$$$(null, -1, 16, openSerialPortBtn.getFont());
        if (openSerialPortBtnFont != null) openSerialPortBtn.setFont(openSerialPortBtnFont);
        openSerialPortBtn.setText("打开");
        contentPanel.add(openSerialPortBtn, new GridConstraints(1, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        messageLabel = new JLabel();
        messageLabel.setText("");
        contentPanel.add(messageLabel, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final Spacer spacer2 = new Spacer();
        contentPanel.add(spacer2, new GridConstraints(1, 5, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        final Spacer spacer3 = new Spacer();
        contentPanel.add(spacer3, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
        final Spacer spacer4 = new Spacer();
        contentPanel.add(spacer4, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        scanBtn = new JButton();
        scanBtn.setText("检测");
        contentPanel.add(scanBtn, new GridConstraints(1, 4, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    }

    /**
     * @noinspection ALL
     */
    private Font $$$getFont$$$(String fontName, int style, int size, Font currentFont) {
        if (currentFont == null) return null;
        String resultName;
        if (fontName == null) {
            resultName = currentFont.getName();
        } else {
            Font testFont = new Font(fontName, Font.PLAIN, 10);
            if (testFont.canDisplay('a') && testFont.canDisplay('1')) {
                resultName = fontName;
            } else {
                resultName = currentFont.getName();
            }
        }
        Font font = new Font(resultName, style >= 0 ? style : currentFont.getStyle(), size >= 0 ? size : currentFont.getSize());
        boolean isMac = System.getProperty("os.name", "").toLowerCase(Locale.ENGLISH).startsWith("mac");
        Font fontWithFallback = isMac ? new Font(font.getFamily(), font.getStyle(), font.getSize()) : new StyleContext().getFont(font.getFamily(), font.getStyle(), font.getSize());
        return fontWithFallback instanceof FontUIResource ? fontWithFallback : new FontUIResource(fontWithFallback);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return contentPanel;
    }

}
